#include "stdafx.h"
#include "mp.h"

namespace xm
{
	xman_session_t::xman_session_t( XManEngine * engo, IKDetectSession * sess )
	{
		session = sess;
		xman = engo;
	}

	recp_t * xman_session_t::handle_pattern_hit( p2r_t& prmap )
	{
		ptnp_t * ptnp = get_phdr(prmap.ptndp);
		recp_t * recp = prmap.rhptr;
		rec_score_t& r = score_of_recs[recp];
		if( r._addcount < 0 ) return NULL;
		int32_t iptn_score = (int16_t)ptnp->score;
		int32_t now_score = (r._score += iptn_score);
		r._addcount ++;
		if( recp->opts & mp::RoptHasMinus ) return NULL;
		if( now_score < recp->score ) return NULL;
		r._addcount = -1;
		return handle_record_hit( recp );
	}

	recp_t * xman_session_t::handle_record_hit( recp_t * recp )
	{
		bool_t logmode = (session->DetectOptions() & DOSCAN_LOGDR);
		if( recp->rcls < RclsMalware || logmode )
		{
			DetectResult dr = {};
			dr.Level = ( recp->rcls < RclsMalware ) ? DLEV_NOT_MALW : DLEV_MALW_EXACT;
			dr.Name = namep(recp);
			dr.SigId = recp->sigid;
			session->PushResult( dr );
			return NULL;
		}
		return logmode ? NULL : recp;
	}

	void xman_session_t::clear()
	{
		score_of_recs.clear();
	}

	recp_t * xman_session_t::handle_hitted_mius_records()
	{
		score_vector_t::iterator it = score_of_recs.begin();

		recp_t * hit_rec = 0;
		for( ; it != score_of_recs.end(); ++ it )
		{
			rec_score_t & r = it->second;
			if( r._addcount < 0 ) continue;

			recp_t * recp = it->first;
			if( r._score < (int32_t)recp->score )
				continue;

			r._addcount = -1;

			if( !hit_rec ) 
				hit_rec = handle_record_hit( hit_rec );
		}
		return hit_rec;
	}

};
